package com.tjf.myjetpackdemo.RxObserverModel;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: tjf
 * @date: 2023-06-08
 * @desc：  被观察者的线程
 */
public class ObservableSubscribeOn<T> extends AbstractObservableWithUpstream<T, T> {

    final static ExecutorService executorService = Executors.newCachedThreadPool();


    protected ObservableSubscribeOn(ObservableSource<T> source) {
        super(source);

    }

    @Override
    protected void subscribeActual(final Observer<T> observer) {
        final SubscribeOnObserver<T> onObserver = new SubscribeOnObserver<>(observer);
        observer.onSubscribe();
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                source.subscribe(onObserver);
            }
        });
    }

    static final class SubscribeOnObserver<T> implements Observer<T> {

        final Observer<T> actual;

        SubscribeOnObserver(Observer<T> actual) {
            this.actual = actual;
        }

        @Override
        public void onSubscribe() {
            actual.onSubscribe();
        }

        @Override
        public void onNext(T t) {
            actual.onNext(t);
        }

        @Override
        public void onError(Throwable throwable) {
            actual.onError(throwable);
        }

        @Override
        public void onComplete() {
            actual.onComplete();
        }
    }
}
